const db = require('../config/db');
const bcrypt = require('bcryptjs');

const createUser = async (username, email, password) => {
  const hashedPassword = await bcrypt.hash(password, 10);
  const [result] = await db.query(
    'INSERT INTO users (username, email, password) VALUES (?, ?, ?)',
    [username, email, hashedPassword]
  );
  return result.insertId;
};

const findUserByEmail = async (email) => {
  const [rows] = await db.query('SELECT * FROM users WHERE email = ?', [email]);
  return rows[0];
};

const findUserById = async (id) => {
  const [rows] = await db.query('SELECT id, username, email, avatar FROM users WHERE id = ?', [id]);
  return rows[0];
};

const updateUserProfile = async (id, username, email) => {
  await db.query(
    'UPDATE users SET username = ?, email = ? WHERE id = ?',
    [username, email, id]
  );
};

const updateUserAvatar = async (id, avatar) => {
  await db.query(
    'UPDATE users SET avatar = ? WHERE id = ?',
    [avatar, id]
  );
};

const comparePassword = async (password, hashedPassword) => {
  return await bcrypt.compare(password, hashedPassword);
};

module.exports = {
  createUser,
  findUserByEmail,
  findUserById,
  updateUserProfile,
  updateUserAvatar,
  comparePassword
};